package com.jy.datapipeline.common.util;

import com.cronutils.model.definition.CronDefinition;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.model.time.ExecutionTime;
import com.cronutils.parser.CronParser;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;

import static com.cronutils.model.CronType.QUARTZ;
@Slf4j
public class CronUtils {

    public static     CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(QUARTZ);

    public static  CronParser parser = new CronParser(cronDefinition);


    public static String nextExecution(String cronStr){
        try {
            ExecutionTime executionTime = ExecutionTime.forCron(CronUtils.parser.parse(cronStr));
            Optional<ZonedDateTime> zonedDateTime = executionTime.nextExecution(ZonedDateTime.now());
            return zonedDateTime.get().format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
        }catch (Exception e){
            log.error("nextExecution error");
            return null;
        }

    }


    public static String lastExecution(String cronStr){
        try {
            ExecutionTime executionTime = ExecutionTime.forCron(CronUtils.parser.parse(cronStr));
            Optional<ZonedDateTime> zonedDateTime1 = executionTime.lastExecution(ZonedDateTime.now());
            return zonedDateTime1.toString();
        }catch (Exception e){
            log.error("lastExecution error");
            return  null;
        }

    }

    public static void main(String[] args) {
      System.out.println( CronUtils.nextExecution("0 */2 * * * ?"));
    }
}
